// app.js
//--------
//消息协议
var SocketMessage = require('./utils/SocketMessage.js')
//时间工具
var timeUtil = require('./utils/Time.js')
//--------
var socketOpen = false
let frameBuffer_Data, session, SocketTask
var url = 'xxxxxxx?userId='
//心跳处理相关变量
var lockReconnect = false //避免重复连接
var ws
var tt
import getUserInfo from './utils/getUserInfo'
import { request } from './request/index'

var that
App({
  globalData: {
    userInfo: null,
    wdxx: 0,
    Socket: null,
    qtype: 0
  },
  onLaunch() {
    wx.setStorageSync('status', 0)
    that = this
    // 获取用户信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          // wx.getUserInfo({
          //   success: (res) => {
          //     // 可以将 res 发送给后台解码出 unionId
          //     this.globalData.userInfo = res.userInfo
          //     console.log(res.userInfo)
          //     // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          //     // 所以此处加入 callback 以防止这种情况
          //     if (this.userInfoReadyCallback) {
          //       this.userInfoReadyCallback(res)
          //     }
          //   }
          // })
        }
      }
    })

    // 检查用户登录状态是否过期
    this.checkLogin()
  },
  onHide() {
    this.globalData.wdxx = 0
    // 删除本地未读消息,下次会从后端库里重新获得
    let userLie = wx.getStorageSync('userLie')
    let message = wx.getStorageSync('message')
    let pl = wx.getStorageSync('pinglun')
    let dianzang = wx.getStorageSync('dianzang')
    let sonli = wx.getStorageSync('sonli')
    let xitong = wx.getStorageSync('xitong')

    if (userLie.length > 0) {
      userLie.forEach((item) => {
        if (item.weidu > 0) {
          message[item.chatId] = message[item.chatId].filter((val) => {
            if (val['isku']) {
              item.weidu -= 1
              // this.globalData.wdxx -= 1
            } else {
              return true
            }
          })
        }
      })
    }

    if (pl.length > 0) {
      pl = pl.filter((item) => {
        if (item['isweidu'] && item['isku']) {
          // this.globalData.wdxx -= 1
          // return true
          console.log(1)
        } else {
          return true
        }
      })
    }
    if (dianzang.length > 0) {
      dianzang = dianzang.filter((item) => {
        if (item['isweidu'] && item['isku']) {
          // this.globalData.wdxx -= 1
          // return true
          console.log(1)
        } else {
          return true
        }
      })
    }
    if (sonli.length > 0) {
      sonli = sonli.filter((item) => {
        if (item['isweidu'] && item['isku']) {
          // this.globalData.wdxx -= 1
          // return true
          console.log(1)
        } else {
          return true
        }
      })
    }
    if (xitong.length > 0) {
      xitong = xitong.filter((item) => {
        if (item['isweidu'] && item['isku']) {
          // this.globalData.wdxx -= 1
          // return true
          console.log(1)
        } else {
          return true
        }
      })
    }

    wx.setStorageSync('message', message)
    wx.setStorageSync('userLie', userLie)
    wx.setStorageSync('pinglun', pl)
    wx.setStorageSync('dianzang', dianzang)
    wx.setStorageSync('sonli', sonli)
    wx.setStorageSync('xitong', xitong)
  },
  async onShow() {
    let userLie = wx.getStorageSync('userLie')
    let pl = wx.getStorageSync('pinglun')
    let dianzang = wx.getStorageSync('dianzang')
    let sonli = wx.getStorageSync('sonli')
    let xitong = wx.getStorageSync('xitong')
    if (!userLie) userLie = []
    // if (!message) message = {}
    if (!dianzang) dianzang = []
    if (!sonli) sonli = []
    if (!pl) pl = []
    if (!xitong) xitong = []

    // 获得缓存里的未读消息
    if (userLie && userLie.length > 0) {
      userLie.forEach((item) => {
        if (item.weidu > 0) {
          this.globalData.wdxx += item.weidu
        }
      })
    }

    // 获得库里的未读消息
    const userId = wx.getStorageSync('userId')
    if (!userId) return
    const { data } = await request({
      url: `/readMessage/${userId}`,
      dataType: 'json',
      method: 'POST'
    })
    console.log(data)
    let { message } = data
    // if (!message) message = []
    // if (message.length <= 0) return
    let ids = []
    let uInfo
    let messages = wx.getStorageSync('message')
    if (!messages) {
      messages = {}
    }
    let len = 0
    if (message && message.length > 0) {
      message.forEach((item) => {
        if (
          item.messageType == SocketMessage.PRIVATE_CHAT &&
          !ids.includes(item.userId)
        ) {
          ids.push(item.userId)
        }
      })
    }
    if (ids.length > 0) {
      uInfo = await getUserInfo(ids)
    }

    if (message && message.length > 0) {
      message.forEach((item) => {
        item['isku'] = true
        let p = false
        let i = 0
        if (item.messageType == SocketMessage.PRIVATE_CHAT) {
          len += 1
          let user = null
          userLie.some((item1, index) => {
            if (item1.chatId == item.userId) {
              p = true
              i = index
            }
          })
          uInfo.forEach((us) => {
            if (us.id == item.userId) user = us
          })
          if (p === false) {
            userLie.unshift({
              chatId: item.userId,
              isTop: false,
              isTouchMove: false,
              lastmes: item.message,
              lasttime: item.stime,
              name: user.username,
              tou: user.headpic,
              weidu: 1
            })
          } else {
            userLie[i].lastmes = item.message
            userLie[i].lasttime = item.stime
            userLie[i].weidu += 1
          }
          if (!messages[item.userId]) messages[item.userId] = []
          messages[item.userId].push({
            id: 1,
            message: item.message,
            stime: item.stime,
            usernmae: user.username,
            tou: user.headpic,
            // 后端库未读消息标识
            isku: true
          })
        }
        // 点赞未读
        if (item.messageType == SocketMessage.GREAT) {
          item['isweidu'] = true
          dianzang.push(item)
        }
        // 送礼消息未读
        if (item.messageType == SocketMessage.PRESENT) {
          item['isweidu'] = true
          sonli.push(item)
        }
        // 评论回复消息未读
        if (item.messmessageTypeage == SocketMessage.REVIEW) {
          item['isweidu'] = true
          pl.push(item)
        }
        // 系统通知未读
        if (item.messageType == SocketMessage.REVIEW) {
          item['isweidu'] = true
          xitong.push(item)
        }
      })
    }

    if (pl && pl.length > 0) {
      pl.forEach((element) => {
        if (element['isweidu']) len += 1
      })
    }
    if (dianzang && dianzang.length > 0) {
      dianzang.forEach((element) => {
        if (element['isweidu']) len += 1
      })
    }
    if (sonli && sonli.length > 0) {
      sonli.forEach((element) => {
        if (element['isweidu']) len += 1
      })
    }
    if (xitong && xitong.length > 0) {
      xitong.forEach((element) => {
        if (element['isweidu']) len += 1
      })
    }
    // let { wdxx } = getApp().globalData
    // wdxx += len
    this.globalData.wdxx += len

    wx.setStorageSync('message', messages)
    wx.setStorageSync('userLie', userLie)
    wx.setStorageSync('pinglun', pl)
    wx.setStorageSync('dianzang', dianzang)
    wx.setStorageSync('sonli', sonli)
    wx.setStorageSync('xitong', xitong)

    var pages = getCurrentPages()
    var currentPage = pages[pages.length - 1] //当前页面
    if (currentPage?.onMessage) currentPage.onMessage('1', true)
  },

  // 检查用户登录状态是否过期
  checkLogin() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.checkSession({
      success: (result) => {
        console.log(result)
        wx.hideLoading()
        if (!wx.getStorageSync('userInfo')) return

        // 检查token值是否过期
        // const newTime = Date.parse(new Date())
        // const expiration = wx.getStorageSync('expiration')
        // if (!expiration || expiration <= newTime) {
        //   wx.showModal({
        //     title: '提示',
        //     content: '登录已过期,请重新登录!',
        //     showCancel: false,
        //     success: (res) => {
        //       wx.reLaunch({
        //         url: '/pages/login/login'
        //       })
        //     }
        //   })
        //   return
        // }

        //websocket
        const userId = wx.getStorageSync('userId')
        if (userId) {
          webSocket(userId)
          working(userId)
          wx.switchTab({
            url: '/pages/index/index',
            fail: (e) => {
              console.log('跳转到首页失败', e)
            }
          })
        }
      },
      fail: () => {
        wx.hideLoading()
        console.log('用户登录过期请重新登录')
      }
    })
  }
})

//websocket心跳
var heartCheck = {
  timeout: 30000,
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function () {
    console.log('start')
    var self = this
    this.timeoutObj && clearTimeout(this.timeoutObj)
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
    this.timeoutObj = setTimeout(function () {
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //onmessage拿到返回的心跳就说明连接正常
      console.log('发送心跳包')
      SocketTask.send({
        data: JSON.stringify({
          userId: wx.getStorageSync('userId'),
          chatId: 21016,
          message: 'HeartBeat',
          messageType: SocketMessage.HEART_BEAT, //心跳
          stime: timeUtil.formatTime(new Date())
        })
      })
      self.serverTimeoutObj = setTimeout(function () {
        //console.log(SocketTask);
        SocketTask.close() // createWebSocket();
      }, self.timeout)
    }, this.timeout)
  }
}
//websocket事件监听
function working(userId) {
  let _this = this
  SocketTask.onOpen((res) => {
    socketOpen = true
    console.log('监听 WebSocket 连接打开事件。', res) //心跳检测重置
    heartCheck.start()
    that.globalData.Socket = SocketTask
    // globalDataSocket = SocketTask
  })
  SocketTask.onClose((onClose) => {
    console.log('监听 WebSocket 连接关闭事件。', onClose)
    socketOpen = false
    reconnect(userId) //重连
  })
  SocketTask.onError((onError) => {
    console.log('监听 WebSocket 错误。错误信息', onError)
    socketOpen = false
    reconnect(userId)
  })
  SocketTask.onMessage(async (onMessage) => {
    console.log(
      '监听WebSocket接受到服务器的消息事件。服务器返回的消息',
      JSON.parse(onMessage.data)
    )
    var onMessage_data = JSON.parse(onMessage.data)
    // if (onMessage_data.chatId == 3) onMessage_data.username = '小米' //console.log(onMessage_data) //心跳检测重置
    heartCheck.start()
    // 消息接受
    if (onMessage_data.messageType == SocketMessage.PRIVATE_CHAT) {
      let message = wx.getStorageSync('message')
      console.log('开始设置')
      let userLie = wx.getStorageSync('userLie')
      if (!userLie) userLie = []
      if (!message) message = {}
      let p = false
      let i = 0
      userLie.some((item, index) => {
        if (item.chatId == onMessage_data.userId) {
          p = true
          i = index
          return true
        }
      })
      const ids = [onMessage_data.userId]
      const uInfo = await getUserInfo(ids)
      console.log(uInfo)
      if (p === false) {
        userLie.unshift({
          chatId: onMessage_data.userId,
          isTop: false,
          isTouchMove: false,
          lastmes: onMessage_data.message,
          lasttime: onMessage_data.stime,
          name: uInfo[0].username,
          tou: uInfo[0].headpic,
          weidu: 1
        })
      } else {
        userLie[i].lastmes = onMessage_data.message
        userLie[i].lasttime = onMessage_data.stime
        userLie[i].weidu += 1
      }
      if (!message[onMessage_data.userId]) message[onMessage_data.userId] = []
      message[onMessage_data.userId].push({
        id: 1,
        message: onMessage_data.message,
        stime: onMessage_data.stime,
        usernmae: uInfo[0].username,
        tou: uInfo[0].headpic
      })
      wx.setStorageSync('message', message)
      wx.setStorageSync('userLie', userLie)
      getApp().globalData.wdxx += 1
    }
    // 点赞
    if (onMessage_data.messageType == SocketMessage.GREAT) {
      onMessage_data['isweidu'] = true
      let dianzang = wx.getStorageSync('dianzang')
      if (!dianzang) dianzang = []
      dianzang.push(onMessage_data)
      getApp().globalData.wdxx += 1
      wx.setStorageSync('dianzang', dianzang)
    }
    // 送礼消息
    if (onMessage_data.messageType == SocketMessage.PRESENT) {
      onMessage_data['isweidu'] = true
      let sonli = wx.getStorageSync('sonli')
      if (!sonli) sonli = []
      sonli.push(onMessage_data)
      getApp().globalData.wdxx += 1
      wx.setStorageSync('sonli', sonli)
    }
    // 评论回复消息
    if (onMessage_data.messageType == SocketMessage.REVIEW) {
      onMessage_data['isweidu'] = true
      let pinglun = wx.getStorageSync('pinglun')
      if (!pinglun) pinglun = []
      pinglun.push(onMessage_data)
      getApp().globalData.wdxx += 1
      wx.setStorageSync('pinglun', pinglun)
    }
    // 系统通知
    if (onMessage_data.messageType == SocketMessage.SYSTEM) {
      onMessage_data['isweidu'] = true
      let xitong = wx.getStorageSync('xitong')
      if (!xitong) xitong = []
      xitong.push(onMessage_data)
      getApp().globalData.wdxx += 1
      wx.setStorageSync('xitong', xitong)
    }
    var pages = getCurrentPages()
    var currentPage = pages[pages.length - 1] //当前页面
    if (currentPage.onMessage) currentPage.onMessage(onMessage_data)
  })
}
//websocket
function webSocket(userId) {
  let _this = this // 创建Socket
  SocketTask = wx.connectSocket({
    url: url + userId,
    data: 'data',
    header: {
      'content-type': 'application/json'
    },
    method: 'post',
    success: function (res) {
      socketOpen = true
      console.log('WebSocket连接创建', res)
    },
    fail: function (err) {
      wx.showToast({
        title: '网络异常！'
      })
      console.log(err)
    }
  })
  return SocketTask
}
//重连
function reconnect(userId) {
  let that = this
  if (lockReconnect) {
    return
  }
  lockReconnect = true //没连接上会一直重连，设置延迟避免请求过多
  tt && clearTimeout(tt)
  tt = setTimeout(function () {
    webSocket(userId)
    working(userId)
    lockReconnect = false
  }, 5000)
}

//外面页面可以调用SocketTask来监听OnMessahe事件
module.exports = {
  SocketTask: SocketTask,
  webSocket,
  working
}
